package com.project_doctor.handler;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.lang.Long;
import java.util.stream.Collectors;

public class LongListConverter implements Converter<List<Long>> {
    private static final Logger log = LoggerFactory.getLogger(LongListConverter.class);

    @Override
    public Class<List<Long>> supportJavaTypeKey() {
        // 通过匿名内部类获取带泛型的TypeReference
        Type type = new TypeReference<List<Long>>() {}.getType();
        return (Class<List<Long>>) ((ParameterizedType) type).getRawType();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public WriteCellData<?> convertToExcelData(List<Long> value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        log.info("导出List<Long>数据：{}", value);
        if (value == null || value.isEmpty()) {
            return new WriteCellData<>("[]");
        }
        try {
            return new WriteCellData<>(JSONArray.toJSONString(value));
        } catch (JSONException e) {
            log.error("导出JSON数组失败，回退为逗号分隔字符串", e);
            return new WriteCellData<>(value.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(",")));
        }
    }

    @Override
    public List<Long> convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                        GlobalConfiguration globalConfiguration) {
        String cellValue = cellData != null ? cellData.getStringValue() : null;
        log.info("导入单元格数据：{}", cellValue);

        if (cellValue == null) {
            return new ArrayList<>();
        }

        String trimmedValue = cellValue.trim();
        List<Long> result = new ArrayList<>();

        if (trimmedValue.startsWith("[") && trimmedValue.endsWith("]")) {
            try {
                JSONArray array = JSONArray.parseArray(trimmedValue);
                for (int i = 0; i < array.size(); i++) {
                    Object item = array.get(i);
                    if (item instanceof Long) {
                        result.add((Long) item);
                    } else if (item instanceof Integer) {
                        result.add(((Integer) item).longValue());
                    } else if (item instanceof String) {
                        try {
                            result.add(Long.parseLong((String) item));
                        } catch (NumberFormatException e) {
                            log.warn("字符串转换为Long失败：{}", item);
                        }
                    } else {
                        log.warn("不支持的类型：{}，值：{}", item.getClass().getName(), item);
                    }
                }
                return result;
            } catch (Exception e) {
                log.error("解析JSON数组失败，尝试按逗号分隔处理", e);
            }
        }

        for (String part : trimmedValue.split(",")) {
            String p = part.trim();
            if (p.isEmpty()) {
                continue;
            }
            try {
                result.add(Long.parseLong(p));
            } catch (NumberFormatException e) {
                log.warn("无效的Long值：{}，已跳过", p);
            }
        }

        return result;
    }
}